﻿using HandyControl.Controls;
using Infov1.Commands;
using Infov1.Models;
using Infov1.Models.Communication;
using Infov1.Models.WorkRecord;
using SqlSugar;
using System;
using System.Windows;
using System.Collections.ObjectModel;
using System.Windows.Input;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Messaging;

namespace Infov1.ViewModels.WorkRecord
{
    /// <summary>
    /// 工作记录ViewModel
    /// </summary>
    public class WorkRecordViewModel : ViewModelBase
    {
        #region 私有字段
        private readonly ISqlSugarClient _db;
        private ObservableCollection<CommunicationTypeModel> _commTypeList;
        private string _customerCode;
        private string _customerName;
        private string _commTypeCode;
        private bool _isRemote;
        private string _details;
        private string _result;
        private string _searchText;
        private int _khId;
        //当前日期 当前时间
        private DateTime _selectedDate = DateTime.Today;
        private DateTime _selectedTime = DateTime.Now;

        #endregion

        #region 构造函数
        public WorkRecordViewModel()
        {
            try
            {
                // 初始化日期和时间
                SelectedDate = DateTime.Today;
                SelectedTime = DateTime.Now;
                //连接数据库
                _db = DbContext.GetConnection();
                ValidateDatabaseConnection();
                InitializeCommands();
                LoadCommTypes();
            }
            catch (Exception ex)
            {
                Growl.Error($"初始化失败: {ex.Message}");
            }
        }
        #endregion

        #region 公共属性
        /// <summary>
        /// 搜索文本
        /// </summary>
        public string SearchText
        {
            get => _searchText;
            set => SetProperty(ref _searchText, value);
        }

        /// <summary>
        /// 客户编码
        /// </summary>
        public string CustomerCode
        {
            get => _customerCode;
            set => SetProperty(ref _customerCode, value);
        }
        /// <summary>
        /// 客户id
        /// </summary>
        public int KhId
        {
            get => _khId;
            set => SetProperty(ref _khId, value);
        }
        /// <summary>
        /// 客户名称
        /// </summary>
        public string CustomerName
        {
            get => _customerName;
            set => SetProperty(ref _customerName, value);
        }
        /// <summary>
        /// 沟通类型列表
        /// </summary>
        public ObservableCollection<CommunicationTypeModel> CommTypeList
        {
            get => _commTypeList;
            set => SetProperty(ref _commTypeList, value);
        }
        /// <summary>
        /// 沟通类型编码
        /// </summary>
        public string CommTypeCode
        {
            get => _commTypeCode;
            set => SetProperty(ref _commTypeCode, value);
        }
        /// <summary>
        /// 是否远程
        /// </summary>
        public bool IsRemote
        {
            get => _isRemote;
            set => SetProperty(ref _isRemote, value);
        }
        // 日期属性
        public DateTime SelectedDate
        {
            get => _selectedDate;
            set => SetProperty(ref _selectedDate, value);
        }

        // 时间属性
        public DateTime SelectedTime
        {
            get => _selectedTime;
            set => SetProperty(ref _selectedTime, value);
        }
        /// <summary>
        /// 详细内容
        /// </summary>
        public string Details
        {
            get => _details;
            set => SetProperty(ref _details, value);
        }
        /// <summary>
        /// 处理结果
        /// </summary>
        public string Result
        {
            get => _result;
            set => SetProperty(ref _result, value);
        }

        /// <summary>
        /// 保存命令
        /// </summary>
        public ICommand SaveCommand { get; private set; }
        /// <summary>
        /// 清除命令
        /// </summary>
        public ICommand ClearCommand { get; private set; }
        #endregion
        #region 公共方法
        /// <summary>
        /// 更新选中的客户信息
        /// </summary>

        public void UpdateSelectedCustomer(CustomerInfoModel customer)
        {
            if (customer != null)
            {
                CustomerCode = customer.CustomerCode;
                CustomerName = customer.CompanyName;
                SearchText = customer.CustomerCode;
                KhId=customer.Id;
            }

        }
        #endregion

        #region 私有方法
        /// <summary>
        /// 验证数据库连接
        /// </summary>
        private void ValidateDatabaseConnection()
        {
            if (_db == null || !_db.Ado.IsValidConnection())
            {
                throw new Exception("数据库连接失败");
            }
        }

        /// <summary>
        /// 初始化命令
        /// </summary>
        private void InitializeCommands()
        {
            SaveCommand = new RelayCommand(SaveRecord);
            ClearCommand = new RelayCommand(ClearForm);
            CommTypeList = new ObservableCollection<CommunicationTypeModel>();
        }

        /// <summary>
        /// 加载沟通类型
        /// </summary>
        private void LoadCommTypes()
        {
            try
            {
                var types = _db.Queryable<CommunicationTypeModel>()
                    .OrderBy(x => x.SortNo)
                    .ToList();

                CommTypeList = new ObservableCollection<CommunicationTypeModel>(types);
                CommTypeCode = "01"; // 默认选择问题类型
            }
            catch (Exception ex)
            {
                Growl.Error($"加载沟通类型失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 保存工作记录
        /// </summary>
        private void SaveRecord()
        {
            try
            {
                ValidateDatabaseConnection();
                // 如果验证不通过，直接返回
                if (!ValidateRequiredFields())
                {
                    Growl.Error("保存失败,请检查填写信息！");
                    return;
                }

                var record = CreateWorkRecord();
                _db.Insertable(record).ExecuteCommand();

                Application.Current.Dispatcher.Invoke(() =>
                {
                    Growl.Success("保存成功");
                  
                    ClearForm();
                });
            }
            catch (Exception ex)
            {
                Growl.Error($"保存失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 验证必填字段
        /// </summary>
        private bool ValidateRequiredFields()
        {
            if (string.IsNullOrWhiteSpace(CustomerCode))
            {
                Growl.Warning("请选择客户");
                return false;
            }

            if (string.IsNullOrWhiteSpace(CommTypeCode))
            {
                Growl.Warning("请选择沟通事项");
                return false;
            }

            if (string.IsNullOrWhiteSpace(Details))
            {
                Growl.Warning("请填写详情");
                return false;
            }

            if (string.IsNullOrWhiteSpace(Result))
            {
                Growl.Warning("请填写处理结果");
                return false;
            }
            if (KhId <= 0)  // 添加 KhId 的验证
            {
                Growl.Warning("无效的客户ID");
                return false;
            }
            return true;
        }
        /// <summary>
        /// 创建工作记录对象
        /// </summary>
        private WorkRecordModel CreateWorkRecord()
        {
            // 如果日期或时间为默认值，使用当前时间
            DateTime dateToUse = (SelectedDate == default(DateTime)) ? DateTime.Today : SelectedDate;
            DateTime timeToUse = (SelectedTime == default(DateTime)) ? DateTime.Now : SelectedTime;

            // 拼接日期和时间
            var combinedDateTime = dateToUse.Date.Add(timeToUse.TimeOfDay);
            return new WorkRecordModel
            {
                CustomerCode = CustomerCode,
                CommTypeCode = CommTypeCode,
                IsRemote = IsRemote,
                Details = Details,
                Result = Result,
                CustomerId = KhId,
                Operator = Application.Current.Properties["AdminName"]?.ToString(),
                CreationTime = combinedDateTime
            };
        }

        /// <summary>
        /// 清除表单
        /// </summary>
        private void ClearForm()
        {
            CustomerCode = string.Empty;
            CustomerName = string.Empty;
            CommTypeCode = "01";
            IsRemote = false;
            KhId = 0;  
            Details = string.Empty;
            Result = string.Empty;
            SearchText = string.Empty;
            // 重置为当前日期和时间
            SelectedDate = DateTime.Today;
            SelectedTime = DateTime.Now;
            Messenger.Default.Send("setFocus", "SetFocus"); //第一个是消息，第二个是token
        }
        #endregion
    }
}